<template>
  <el-dialog
    v-model="dialogVisible"
    title="学习统计"
    width="800px"
    :before-close="handleClose"
  >
    <div class="stats-content" v-loading="loading">
      <!-- 概览卡片 -->
      <div class="overview-cards">
        <div class="stat-card">
          <div class="card-icon questions">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.totalQuestions || 0 }}</div>
            <div class="card-label">总提问数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="card-icon programming">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.programmingQuestions || 0 }}</div>
            <div class="card-label">编程问题</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="card-icon skill">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ skillLevelDisplay }}</div>
            <div class="card-label">技能水平</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="card-icon language">
            <el-icon><Document /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.currentLanguage || '未设置' }}</div>
            <div class="card-label">主要语言</div>
          </div>
        </div>
      </div>
      
      <!-- 学习进展 -->
      <div class="section">
        <h3 class="section-title">
          <el-icon><DataAnalysis /></el-icon>
          学习进展
        </h3>
        
        <div class="progress-content">
          <!-- 技能水平进度 -->
          <div class="progress-item">
            <div class="progress-header">
              <span class="progress-label">技能水平进度</span>
              <span class="progress-value">{{ skillProgress }}%</span>
            </div>
            <el-progress 
              :percentage="skillProgress" 
              :color="skillProgressColor"
              :stroke-width="8"
            />
            <div class="progress-desc">
              基于您的提问质量和频率评估
            </div>
          </div>
          
          <!-- 编程活跃度 -->
          <div class="progress-item">
            <div class="progress-header">
              <span class="progress-label">编程活跃度</span>
              <span class="progress-value">{{ programmingActivity }}%</span>
            </div>
            <el-progress 
              :percentage="programmingActivity" 
              color="#67c23a"
              :stroke-width="8"
            />
            <div class="progress-desc">
              编程相关问题占总问题的比例
            </div>
          </div>
        </div>
      </div>
      
      <!-- 最近话题 -->
      <div class="section">
        <h3 class="section-title">
          <el-icon><Collection /></el-icon>
          最近关注话题
        </h3>
        
        <div class="topics-content">
          <div v-if="stats.recentTopics?.length" class="topic-tags">
            <el-tag
              v-for="topic in stats.recentTopics"
              :key="topic"
              :type="getTopicType(topic)"
              size="large"
              class="topic-tag"
            >
              {{ topic }}
            </el-tag>
          </div>
          <div v-else class="empty-state">
            <el-icon><Document /></el-icon>
            <span>暂无话题记录</span>
          </div>
        </div>
      </div>
      
      <!-- 学习分析 -->
      <div class="section">
        <h3 class="section-title">
          <el-icon><PieChart /></el-icon>
          学习分析
        </h3>
        
        <el-row :gutter="24">
          <!-- 优势领域 -->
          <el-col :span="12">
            <div class="analysis-card">
              <h4 class="analysis-title">
                <el-icon><Trophy /></el-icon>
                优势领域
              </h4>
              <div v-if="stats.strongAreas?.length" class="area-list">
                <div 
                  v-for="area in stats.strongAreas" 
                  :key="area"
                  class="area-item strong"
                >
                  <el-icon><Check /></el-icon>
                  <span>{{ area }}</span>
                </div>
              </div>
              <div v-else class="empty-state">
                <span>继续学习以发现您的优势</span>
              </div>
            </div>
          </el-col>
          
          <!-- 需要改进 -->
          <el-col :span="12">
            <div class="analysis-card">
              <h4 class="analysis-title">
                <el-icon><Warning /></el-icon>
                需要改进
              </h4>
              <div v-if="stats.weakAreas?.length" class="area-list">
                <div 
                  v-for="area in stats.weakAreas" 
                  :key="area"
                  class="area-item weak"
                >
                  <el-icon><Close /></el-icon>
                  <span>{{ area }}</span>
                </div>
              </div>
              <div v-else class="empty-state">
                <span>暂未发现需要改进的领域</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 学习建议 -->
      <div class="section">
        <h3 class="section-title">
          <el-icon><Lightbulb /></el-icon>
          个性化建议
        </h3>
        
        <div class="suggestions-content">
          <div v-for="suggestion in suggestions" :key="suggestion.title" class="suggestion-item">
            <div class="suggestion-icon" :class="suggestion.type">
              <el-icon>
                <component :is="suggestion.icon" />
              </el-icon>
            </div>
            <div class="suggestion-content">
              <div class="suggestion-title">{{ suggestion.title }}</div>
              <div class="suggestion-desc">{{ suggestion.description }}</div>
            </div>
            <div class="suggestion-action">
              <el-button size="small" @click="applySuggestion(suggestion)">
                应用
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 学习时间线 -->
      <div class="section">
        <h3 class="section-title">
          <el-icon><Clock /></el-icon>
          最近活动
        </h3>
        
        <div class="timeline-content">
          <div class="activity-item">
            <div class="activity-time">{{ formatTime(stats.lastActiveAt) }}</div>
            <div class="activity-desc">最后一次活动</div>
          </div>
          
          <!-- 模拟的活动记录 -->
          <div class="activity-item">
            <div class="activity-time">今天</div>
            <div class="activity-desc">提问了 {{ todayQuestions }} 个问题</div>
          </div>
          
          <div class="activity-item">
            <div class="activity-time">本周</div>
            <div class="activity-desc">学习了 {{ weeklyTopics }} 个新话题</div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="exportStats">
          导出数据
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  ChatDotRound, Monitor, TrendCharts, Document, DataAnalysis,
  Collection, PieChart, Trophy, Warning, Check, Close,
  Lightbulb, Clock
} from '@element-plus/icons-vue'
import { enhancedAIApi, aiUtils, type UserLearningStats } from '@/api/enhanced-ai'

interface Props {
  modelValue: boolean
}

interface Suggestion {
  title: string
  description: string
  type: 'info' | 'warning' | 'success'
  icon: string
  action: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// 响应式数据
const loading = ref(false)
const stats = ref<UserLearningStats>({
  totalQuestions: 0,
  programmingQuestions: 0,
  skillLevel: 'BEGINNER',
  currentLanguage: '',
  recentTopics: [],
  weakAreas: [],
  strongAreas: [],
  lastActiveAt: ''
})

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 计算属性
const skillLevelDisplay = computed(() => 
  aiUtils.getSkillLevelDisplayName(stats.value.skillLevel)
)

const skillProgress = computed(() => {
  const levels = ['BEGINNER', 'INTERMEDIATE', 'ADVANCED', 'EXPERT']
  const currentIndex = levels.indexOf(stats.value.skillLevel)
  return ((currentIndex + 1) / levels.length) * 100
})

const skillProgressColor = computed(() => {
  const progress = skillProgress.value
  if (progress <= 25) return '#f56c6c'
  if (progress <= 50) return '#e6a23c'
  if (progress <= 75) return '#409eff'
  return '#67c23a'
})

const programmingActivity = computed(() => {
  const total = stats.value.totalQuestions || 1
  const programming = stats.value.programmingQuestions || 0
  return Math.round((programming / total) * 100)
})

const todayQuestions = computed(() => {
  // 模拟今日提问数
  return Math.floor(Math.random() * 10) + 1
})

const weeklyTopics = computed(() => {
  // 模拟本周话题数
  return stats.value.recentTopics?.length || 0
})

// 个性化建议
const suggestions = computed((): Suggestion[] => {
  const result: Suggestion[] = []
  
  // 基于技能水平的建议
  if (stats.value.skillLevel === 'BEGINNER') {
    result.push({
      title: '加强基础练习',
      description: '建议多做一些基础编程练习，巩固语法和概念',
      type: 'info',
      icon: 'Document',
      action: 'practice_basics'
    })
  }
  
  // 基于活跃度的建议
  if (programmingActivity.value < 50) {
    result.push({
      title: '增加编程相关问题',
      description: '尝试询问更多编程相关的问题，提高学习效率',
      type: 'warning',
      icon: 'Warning',
      action: 'ask_more_programming'
    })
  }
  
  // 基于薄弱环节的建议
  if (stats.value.weakAreas?.length) {
    result.push({
      title: '针对性学习',
      description: `重点关注 ${stats.value.weakAreas.join('、')} 等薄弱环节`,
      type: 'warning',
      icon: 'Warning',
      action: 'focus_weak_areas'
    })
  }
  
  // 通用建议
  result.push({
    title: '保持学习节奏',
    description: '建议每天保持一定的学习时间，持续进步',
    type: 'success',
    icon: 'Check',
    action: 'maintain_rhythm'
  })
  
  return result
})

// 方法
const loadStats = async () => {
  loading.value = true
  try {
    const data = await enhancedAIApi.getUserStats()
    stats.value = data
  } catch (error: any) {
    ElMessage.error('加载统计数据失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const getTopicType = (topic: string) => {
  const typeMap: Record<string, string> = {
    '编程相关': 'primary',
    '代码调试': 'danger',
    '代码审查': 'warning',
    '概念解释': 'info',
    '项目帮助': 'success',
    '学习相关': ''
  }
  return typeMap[topic] || ''
}

const formatTime = (timeStr: string) => {
  if (!timeStr) return '未知'
  
  try {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (days === 0) return '今天'
    if (days === 1) return '昨天'
    if (days < 7) return `${days}天前`
    
    return date.toLocaleDateString('zh-CN')
  } catch (error) {
    return '未知'
  }
}

const applySuggestion = (suggestion: Suggestion) => {
  ElMessage.success(`已应用建议：${suggestion.title}`)
  // TODO: 实现具体的建议应用逻辑
}

const exportStats = () => {
  try {
    const data = {
      ...stats.value,
      exportTime: new Date().toISOString(),
      skillProgress: skillProgress.value,
      programmingActivity: programmingActivity.value
    }
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { 
      type: 'application/json' 
    })
    
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `learning-stats-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible) {
    loadStats()
  }
})
</script>

<style scoped>
.stats-content {
  max-height: 70vh;
  overflow-y: auto;
}

/* 概览卡片 */
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.card-icon.questions {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.programming {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.skill {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.language {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-content {
  flex: 1;
}

.card-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 13px;
  color: #909399;
}

/* 章节 */
.section {
  margin-bottom: 32px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

/* 进度内容 */
.progress-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.progress-item {
  background: #fff;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.progress-label {
  font-weight: 500;
  color: #303133;
}

.progress-value {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.progress-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 话题标签 */
.topics-content {
  background: #fff;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.topic-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.topic-tag {
  cursor: default;
  font-size: 13px;
}

/* 分析卡片 */
.analysis-card {
  background: #fff;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  height: 100%;
}

.analysis-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.area-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.area-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 13px;
}

.area-item.strong {
  background: #f0f9ff;
  color: #1d4ed8;
}

.area-item.weak {
  background: #fef2f2;
  color: #dc2626;
}

/* 建议内容 */
.suggestions-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.suggestion-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: white;
}

.suggestion-icon.info {
  background: #409eff;
}

.suggestion-icon.warning {
  background: #e6a23c;
}

.suggestion-icon.success {
  background: #67c23a;
}

.suggestion-content {
  flex: 1;
}

.suggestion-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.suggestion-desc {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

/* 时间线 */
.timeline-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.activity-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.activity-time {
  font-size: 13px;
  color: #909399;
}

.activity-desc {
  font-size: 14px;
  color: #303133;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 32px;
  color: #909399;
  font-size: 14px;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条 */
.stats-content::-webkit-scrollbar {
  width: 6px;
}

.stats-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.stats-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-card {
    padding: 16px;
    gap: 12px;
  }
  
  .card-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
  
  .card-number {
    font-size: 20px;
  }
  
  .progress-content {
    gap: 16px;
  }
  
  .progress-item {
    padding: 16px;
  }
  
  .suggestion-item {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .activity-item {
    flex-direction: column;
    gap: 4px;
    text-align: center;
  }
}
</style>
